import { useState, forwardRef, useImperativeHandle, useEffect } from "react";
import {
  Text,
  View,
  StyleSheet,
  ActivityIndicator,
  useWindowDimensions,
  BackHandler,
  NativeEventSubscription
} from "react-native";

export type RefMenthodType = {
  show: (msg?: string) => void;
  hide: () => void;
};

// 实体按钮返回监听实例
let backHandler: NativeEventSubscription | null = null;

const Loading = forwardRef((_props: any, ref: any) => {
  const [visible, setVisible] = useState(false);
  const [text, setText] = useState("正在加载...");
  const { width, height } = useWindowDimensions();

  const show = (msg?: string) => {
    if (msg) setText(msg);
    setVisible(true);
  };
  const hide = () => setVisible(false);

  // 暴露指定的数据给外部使用
  useImperativeHandle(ref, () => {
    return { show, hide };
  });

  useEffect(() => {
    // 监听实体按钮返回
    backHandler = BackHandler.addEventListener("hardwareBackPress", () => {
      // 当前处于下载则禁止返回
      if (visible) {
        console.log("当前处于loading禁止返回");
        return false;
        // 否则直接返回
      } else {
        console.log("直接返回");
        return false;
      }
    });

    return () => {
      if (backHandler) {
        backHandler.remove();
        backHandler = null;
      }
    };
  }, [visible]);

  const LoadContent = (
    <View style={[styles.LoadingPage, { height, width }]}>
      <View style={styles.loadingComtent}>
        <ActivityIndicator size={50} color="#FFF" />
        <Text style={styles.loadingText}>{text}</Text>
      </View>
    </View>
  );

  return visible ? LoadContent : <View></View>;
});

Loading.displayName = "Loading";

const styles = StyleSheet.create({
  LoadingPage: {
    position: "absolute",
    left: 0,
    top: 0,
    backgroundColor: "rgba(0,0,0,0)",
    justifyContent: "center",
    alignItems: "center"
  },
  loadingComtent: {
    width: 150,
    height: 150,
    backgroundColor: "rgba(0,0,0,0.6)",
    opacity: 1,
    justifyContent: "center",
    alignItems: "center",
    borderRadius: 7
  },
  loadingText: {
    marginLeft: 10,
    color: "#FFF",
    marginTop: 10
  }
});

export default Loading;
